package com.dc2013.network;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import android.os.Handler;
import ch.boye.httpclientandroidlib.entity.mime.MultipartEntity;
import ch.boye.httpclientandroidlib.entity.mime.content.FileBody;
import ch.boye.httpclientandroidlib.entity.mime.content.StringBody;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;

public class MultipartRequest extends Request<String> {

	private MultipartEntity entity = new MultipartEntity();

	private static final String FILE_PART_NAME = "file";
	private static final String STRING_PART_NAME = "text";

	private final Response.Listener<String> mListener;
	private final File mFilePart;
	private final String mStringPart;
	private String access_Token, theme_Code;

	public MultipartRequest(String url, Response.ErrorListener errorListener,
			Response.Listener<String> listener, File file, String stringPart,
			String access_Token, String theme_Code) {
		super(Method.POST, url, errorListener);

		mListener = listener;
		mFilePart = file;
		mStringPart = stringPart;
		this.access_Token = access_Token;
		this.theme_Code = theme_Code;
		buildMultipartEntity();

	}

	private void buildMultipartEntity() {
		entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
		try {
			entity.addPart(STRING_PART_NAME, new StringBody(mStringPart));
		} catch (UnsupportedEncodingException e) {
			VolleyLog.e("UnsupportedEncodingException");
		}
	}

	@Override
	public String getBodyContentType() {
		return entity.getContentType().getValue();
	}

	@Override
	public byte[] getBody() throws AuthFailureError {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			entity.writeTo(bos);
		} catch (IOException e) {
			VolleyLog.e("IOException writing to ByteArrayOutputStream");
		}
		return bos.toByteArray();
	}

	@Override
	protected Response<String> parseNetworkResponse(NetworkResponse response) {
		return Response.success("Uploaded", getCacheEntry());
	}

	@Override
	protected void deliverResponse(String response) {
		mListener.onResponse(response);
	}

	@Override
	protected Map<String, String> getParams() throws AuthFailureError {
		// TODO Auto-generated method stub
		Map<String, String> map = new HashMap<String, String>();
		map.put("access_token", access_Token);
		map.put("theme_code", theme_Code);
		return map;
	}
}